package com.sllp.C71S3TsllpShop.biz.impl;


import java.math.BigDecimal;
import java.net.URI;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionContext;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.sllp.C71S3TsllpShop.bean.Address;
import com.sllp.C71S3TsllpShop.bean.AddressExample;
import com.sllp.C71S3TsllpShop.bean.Car;
import com.sllp.C71S3TsllpShop.bean.CarExample;
import com.sllp.C71S3TsllpShop.bean.Orders;
import com.sllp.C71S3TsllpShop.bean.OrdersItem;
import com.sllp.C71S3TsllpShop.bean.Product;
import com.sllp.C71S3TsllpShop.bean.ProductExample;
import com.sllp.C71S3TsllpShop.bean.Specs;
import com.sllp.C71S3TsllpShop.bean.SpecsExample;
import com.sllp.C71S3TsllpShop.bean.Result;
import com.sllp.C71S3TsllpShop.bean.User;

import com.sllp.C71S3TsllpShop.bean.CarExample.Criteria;

import com.sllp.C71S3TsllpShop.biz.CarBiz;
import com.sllp.C71S3TsllpShop.dao.AddressMapper;
import com.sllp.C71S3TsllpShop.dao.CarMapper;

import com.sllp.C71S3TsllpShop.dao.OrdersItemMapper;
import com.sllp.C71S3TsllpShop.dao.OrdersMapper;
import com.sllp.C71S3TsllpShop.dao.ProductMapper;
import com.sllp.C71S3TsllpShop.dao.SpecsMapper;
import com.sllp.C71S3TsllpShop.dao.UserMapper;

//@SessionAttributes({"Totel","Ordersid"})
@Service
public class CarBizImpl implements CarBiz {
	
	
	@Resource
	private SpecsMapper sm;
	
	@Resource
	private AddressMapper am;
	
	@Resource
	private CarMapper cm;
	
	@Resource
	private UserMapper um;
	
	@Resource
	private OrdersMapper om;
	
	@Resource
	private OrdersItemMapper oim;
	
	@Resource
	private ProductMapper pm;

	//加入购物车
	public Result addToCar(Car car) {
		int i;
		int state = 2;//默认未加入购物车购物车
		List<Car> car2 = new ArrayList<>();
		CarExample example = new CarExample();
		example.createCriteria().andUserEqualTo(car.getUser()).andSpecsEqualTo(car.getSpecs());
		car2 = cm.selectByExample(example);
		if(car2.size()>0  && car2.get(0).getState()==2) {
			// 如果购物车中已经有该商品则修改购物车中的数量
			car.setId(car2.get(0).getId());
			car.setCount(car.getCount()+car2.get(0).getCount());
			i = cm.updateByPrimaryKeySelective(car);
			
		}else {
			car.setState(state);
			i = cm.insert(car);
		}
		if(i>=1) {
			return new Result(1, "添加成功");
		}else {
			return new Result(2,"添加失败");
		}
	}
	//修改订单用户信息
	public int modifyUser2(int uid,String useraddr,String userpostal,String usertel) {
		int ok;
		Address address =new Address();
		List<Address> address1 =new ArrayList<Address>();
		int state =2;//默认地址为已启用
		AddressExample ae =new AddressExample();
		//构建条件
		ae.createCriteria().andNameEqualTo(useraddr).andUserEqualTo(uid);
		address1=am.selectByExample(ae);
		//判断增添地址 还是更新地址信息
		if(address1.size() > 0) {
			address.setPostal(userpostal);
			address.setTel(usertel);
			ae.createCriteria().andUserEqualTo(uid).andNameEqualTo(useraddr);
			ok=am.updateByExampleSelective(address, ae);
			if(ok>=1) {
				return 1;
			}else {
				return 0;
			}

		}else {
			address.setUser(uid);
			address.setName(useraddr);
			address.setPostal(userpostal);
			address.setTel(usertel);
			address.setState(state);
			ok=am.insert(address);
			if(ok>=1) {
				return 1;
			}else {
				return 0;
			}
		}
		
	}
	
	
	//修改购物车信息
	public int modifyCar2(int count,int carid) {
		
		int ok;
		Car car =new Car();
//		CarExample ce =new CarExample();
//		//构建条件
//		ce.createCriteria().andIdEqualTo(carid);
		car.setCount(count);
		car.setId(carid);
		System.out.println(car);
		ok=cm.updateByPrimaryKeySelective(car);
		if(ok>=1) {
			return 1;
		}else {
			return 0;
		}
		
	}
	
	//删除购物车信息
	public int deleteCar2(int specs) {
		int ok=0;
		CarExample ce =new CarExample();
		//构建条件
		ce.createCriteria().andSpecsEqualTo(specs);
		ok=cm.deleteByExample(ce);
		if(ok>0) {
			return 1;
		}else {
			return 0;
		}
		
	}
		
		
		
		//商品信息
		/**
		 * 
		 * @param tp 订单总价
		 * @param text 物流公司
		 * @return
		 */
		public int Settle2( User user,BigDecimal tp ,String text,HttpSession session ) {
			
			
			int ok =0;
			//获取当前时间
			Timestamp d = new Timestamp(System.currentTimeMillis());
			
			
			
			Orders orders =new Orders();
			OrdersItem ordersItem =new OrdersItem();
			List<Specs> specslist =new ArrayList<Specs>();
			Specs specs =new Specs();
			int specsnum=0;
			
			User u =um.selectByPrimaryKey(user.getId());
			CarExample ce =new CarExample();
			//构建条件
			Criteria c=ce.createCriteria();	
			c.andUserEqualTo(u.getId()).andStateEqualTo(2);
			List<Car> list = cm.selectByExample(ce);
			
			
			//order表的添加（订单信息）
			//创建订单编号
			int i =0;
			Date day=new Date();    
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHH"); 
			String time = df.format(day);
			StringBuffer  buffer=new StringBuffer();
			buffer.append(time);
			buffer.append(String.valueOf(System.currentTimeMillis()).substring(5));
			
			//根据用户id除以十的余数来判断插入的位置(插入用户id)
			i = u.getId()%10; 
			
			//获取订单编号
			String ordersid=buffer.insert(i, i).toString();
			session.setAttribute("Ordersid", ordersid);
			session.setAttribute("Totel", tp);
			
			
			//添加
			orders.setId(null);
			orders.setOrderId(ordersid);
			orders.setTotal(tp);
			orders.setOrderTime(d);
			/**
			 * 地址添加有问题现在待定
			 */
			orders.setAddr(u.getAddr());
			orders.setUser(u.getId());
			ok =om.insert(orders);
			//判断order表是否添加成功 
			if(ok==0) {
				return 0;
			}else {
				//成功添加oders表后继续ordersItem表的添加（商品结算）
				BigDecimal number = new BigDecimal(0);//用于将商品数量转为Bigdecimal属性
				for(int x=0;x<list.size();x++) {
					int value=list.get(x).getCount();
					number=BigDecimal.valueOf((int)value);
					
					StringBuffer buffer2 = new StringBuffer();
					buffer2.append(System.currentTimeMillis());
					String orderItemId=buffer2.insert(i, i).toString()+((int)Math.random()*10000);
					ordersItem.setId(orderItemId);
					ordersItem.setCount(list.get(x).getCount()); //商品数量
					/**
					 * 修改商品的库存
					 */
					specslist=sm.selectByPrimaryKey(list.get(x).getSpecs());
					specsnum=specslist.get(0).getProductNum();
					specsnum=specsnum-list.get(x).getCount();
					specs.setProductNum(specsnum);
					SpecsExample se =new SpecsExample();
					se.createCriteria().andIdEqualTo(list.get(x).getSpecs());
					ok=sm.updateByExampleSelective(specs, se);
					System.out.println(ok+"==================");
					if(ok==0) {
						return 0;
					}
					
					/**
					 * 修改商品的购买人数
					 */
					int buynum;
					Product p =new Product();
					p=pm.selectByPrimaryKey(list.get(x).getProductSpecs().getProduct());
					buynum=p.getBuyNum()+1;
					p.setBuyNum(buynum);
					ProductExample pe =new ProductExample();
					pe.createCriteria().andIdEqualTo(list.get(x).getProductSpecs().getProduct());
					ok=pm.updateByExampleSelective(p, pe);
					if(ok==0) {
						return 0;
					}
					ordersItem.setSubTotal(list.get(x).getProductSpecs().getProductPrice().multiply(number));//每一种商品价格
					ordersItem.setSpecs(list.get(x).getSpecs());//商品小类型id
					
					ordersItem.setLogistics(text);
					ordersItem.setOrders(orders.getId());
					/**
					 * 商品的出售状态待定为未出售
					 */
					ordersItem.setState(1);
					ok = oim.insert(ordersItem);
					
					CarExample cae =new CarExample();
					cae.createCriteria().andIdEqualTo(list.get(x).getId());
					Car car =new Car();
					car.setState(1);
					cm.updateByExampleSelective(car, cae);
				}
				
				if(ok>0) {
					return 1;
				}
				
			}
			return 0;
		}
		
		//购物车界面一显示
		public List<Car> Cart2(int u) {
			User user = um.selectByPrimaryKey(u);
			CarExample ce = new CarExample();
			// 构建条件
			Criteria c = ce.createCriteria();
			c.andUserEqualTo(user.getId());
			//购物车商品信息为 2：启用状态 才能显示
			c.andStateEqualTo(2);
			List<Car> list = cm.selectByExample(ce);
			return list;
		}
		
		//购物车界面二显示
		public List<Object> Carttwo2(int u) {
			List<Object> obj =new ArrayList<Object>();
			User user =um.selectByPrimaryKey(u);
		
			
			CarExample ce =new CarExample();
			//构建条件
			Criteria c=ce.createCriteria();	
			c.andUserEqualTo(user.getId());
			//商品信息为 2：启用状态 才能显示
			c.andStateEqualTo(2);
			List<Car> list = cm.selectByExample(ce);
			
			//查询用户所有的地址
			AddressExample ae=new AddressExample();
			ae.createCriteria().andUserEqualTo(user.getId());
		    List<Address>alist=am.selectByExample(ae);
			
			
			obj.add(list);
			obj.add(user);
			obj.add(alist);
		
			return obj;
		}
		
		//购物车界面三
		public void Carthree3(HttpSession session) {
			
		
			
			int value=1;
		
			String tp=(String) session.getAttribute("Totel");
			String id=(String)session.getAttribute("Ordersid");
			System.out.println("Totel"+tp);
			System.out.println("Ordersid"+id);
			List<Object> list =new ArrayList<Object>();
			
			
		}
		
		
		//   人物信息显示
		public List<Address> Addrsstwo(int u) {
			u=1;
			User user =um.selectByPrimaryKey(1);
		
			//查询用户所有的地址
			AddressExample ae=new AddressExample();
			com.sllp.C71S3TsllpShop.bean.AddressExample.Criteria a =ae.createCriteria();
			a.andUserEqualTo(user.getId());
		    List<Address>alist=am.selectByExample(ae);
		
			return alist;
		}
		
		
		//主页面的购物车浮框显示
		public List<Car> findCar(User user){
			CarExample ce =new CarExample();
			//构建条件
			Criteria c=ce.createCriteria();	
			c.andUserEqualTo(user.getId()).andStateEqualTo(2);
			List<Car> list = cm.selectByExample(ce);
			return list;
		}
	

}
